package com.example.choupaiapp.main.fragment.mine;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.fragment.CommonFragment;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.activity.mine.MineVideoDetailActivity;
import com.example.choupaiapp.main.bean.MineVideoListBean;
import com.example.choupaiapp.main.constant.Url;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by ASUS on 2019/10/30.
 */

public class MineVideoFragment extends CommonFragment implements OnRefreshLoadMoreListener {
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    Unbinder unbinder;
    private String userid;
    private int contentHidden;
    private int pageNum = 1;
    private int pageSize = 10;
    private BaseQuickAdapter<MineVideoListBean.PageBean.ListBean, BaseViewHolder> quickAdapter;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private String isSelf;
    @BindView(R.id.empty_img)
    ImageView empty_img;

    public static MineVideoFragment newInstance(String userid, String isSelf, int contentHidden) {
        MineVideoFragment mineVideoFragment = new MineVideoFragment();
        mineVideoFragment.userid = userid;
        mineVideoFragment.isSelf = isSelf;
        mineVideoFragment.contentHidden = contentHidden;
        return mineVideoFragment;
    }

    public String formatSeconds(long seconds) {
        String standardTime;
        if (seconds <= 0) {
            standardTime = "00:00";
        } else if (seconds < 60) {
            standardTime = String.format(Locale.getDefault(), "00:%02d", seconds % 60);
        } else if (seconds < 3600) {
            standardTime = String.format(Locale.getDefault(), "%02d:%02d", seconds / 60, seconds % 60);
        } else {
            standardTime = String.format(Locale.getDefault(), "%02d:%02d:%02d", seconds / 3600, seconds % 3600 / 60, seconds % 60);
        }
        return standardTime;
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_img, container, false);
        unbinder = ButterKnife.bind(this, view);

        EventBus.getDefault().register(this);

        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));

        quickAdapter = new BaseQuickAdapter<MineVideoListBean.PageBean.ListBean, BaseViewHolder>(R.layout.item_video_img) {
            @Override
            protected void convert(BaseViewHolder helper, MineVideoListBean.PageBean.ListBean item) {
                ImageView img = helper.getView(R.id.img);
                Glide.with(context)
                        .load(item.getUrls() + "?vframe/jpg/offset/1")
                        .error(R.color.color_f3f3)
                        .centerCrop()
                        .into(img);

                TextView time = helper.getView(R.id.time);

                time.setText(formatSeconds(item.getVideoDuration()));

            }
        };

        GridLayoutManager layoutManager = new GridLayoutManager(context, 2, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(quickAdapter);

        quickAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                //跳转 播放自己全部视频
                Bundle bundle = new Bundle();
                bundle.putInt("position", position);
                bundle.putInt("pageSize", quickAdapter.getItemCount());
                bundle.putString("isSelf", isSelf);
                bundle.putString("userid", userid);
                startActivity(MineVideoDetailActivity.class, bundle);
            }
        });


        return view;
    }


    @Override
    protected void initData() {
        HttpParams params = new HttpParams();
        params.put("userId", userid);
        params.put("type", 1);
        params.put("limit", pageSize);
        params.put("page", pageNum++);
        params.put("isSelf", isSelf);
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.WATCH_CONTENT, params, Url.WATCH_CONTENT, new Callback<MineVideoListBean>() {
            @Override
            public void onSuccess(MineVideoListBean mineVideoListBean) {
                if (mineVideoListBean.getCode() == Contacts.SUCCESS) {
                    if (pageNum - 1 == 1) {
                        if (mineVideoListBean.getPage().getList().size() == 0) {
                            empty_img.setVisibility(View.VISIBLE);
                            if ("1".equals(isSelf)) {
                                empty_img.setImageResource(R.mipmap.icon_mine_empty);
                            } else {
                                if (contentHidden == 1) {
                                    empty_img.setImageResource(R.mipmap.icon_content_hidden);
                                } else {
                                    empty_img.setImageResource(R.mipmap.icon_coment_empty);
                                }
                            }
                        } else {
                            empty_img.setVisibility(View.GONE);
                        }
                        quickAdapter.setNewData(mineVideoListBean.getPage().getList());
                    } else {
                        quickAdapter.addData(mineVideoListBean.getPage().getList());
                    }
                    refreshLayout.finishLoadMore();
                    quickAdapter.notifyDataSetChanged();

                    int pagecount;
                    if (mineVideoListBean.getPage().getTotalCount() % pageSize == 0) {
                        pagecount = mineVideoListBean.getPage().getTotalCount() / pageSize;
                    } else {
                        pagecount = mineVideoListBean.getPage().getTotalCount() / pageSize + 1;
                    }

                    if (pageNum > pagecount) {
                        refreshLayout.setNoMoreData(true);
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.setNoMoreData(false);
                    }
                } else {
                    if (pageNum - 1 == 1) {
                        empty_img.setVisibility(View.VISIBLE);
                        if ("1".equals(isSelf)) {
                            empty_img.setImageResource(R.mipmap.icon_no_net);
                        } else {
                            if (contentHidden == 1) {
                                empty_img.setImageResource(R.mipmap.icon_content_hidden);
                            } else {
                                empty_img.setImageResource(R.mipmap.icon_mine_empty);
                            }
                        }
                    } else {
                        empty_img.setVisibility(View.GONE);
                    }
                    refreshLayout.finishLoadMore();
                    if (mineVideoListBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(mineVideoListBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                if (empty_img != null) {
                    if (pageNum - 1 == 1) {
                        empty_img.setVisibility(View.VISIBLE);
                        empty_img.setImageResource(R.mipmap.icon_no_net);
                    } else {
                        empty_img.setVisibility(View.GONE);
                    }
                }
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                }
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        String s = event.split(":")[0];
        if (s.equals("refresh_mine_tab_data")) {
            pageNum = 1;
            initData();
        } else if (s.equals("scollTo_mine_top")) {
            if ("2".equals(event.split(":")[1])) {
                recyclerView.scrollToPosition(0);
            }
        } else if (s.equals("refresh_mine_data")) {
            if ("2".equals(event.split(":")[1])) {
                pageNum = 1;
                initData();
            }
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        initData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

    }
}
